package org.wlgzs.shop.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.User;
import org.apache.http.HttpRequest;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.wlgzs.shop.bean.*;
import org.wlgzs.shop.config.AlipayConfig;
import org.wlgzs.shop.dao.OrderPersonDataMapper;
import org.wlgzs.shop.dao.OrderTransportDataMapper;
import org.wlgzs.shop.service.ICarDataService;
import org.wlgzs.shop.service.IGoodsDateService;
import org.wlgzs.shop.service.IOrderTransportDateService;
import org.wlgzs.shop.service.IUserDateService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "这是用户的接口", value = "UserController")
@Controller
@RequestMapping(value = "/user")
public class UserDateController {
    @Autowired
    OrderTransportDataMapper orderTransportDataMapper;
    @Autowired
    IUserDateService userDateService;

    @Autowired
    ICarDataService iCarDataService;

    @Autowired
    IGoodsDateService goodsDateService;

    @Autowired
    IOrderTransportDateService iOrderTransportDateService;
    private static final Logger logger = LoggerFactory.getLogger(UserDateController.class);

    /**
     * @param userDate
     * @param result
     * @return Msg
     * <p>
     * 用户注册
     */
    @ResponseBody
    @RequestMapping(value = "/registered")
//    @ApiOperation(value = "注册用户",httpMethod = "POST",response =Msg.class )
    @ApiOperation(value = "用户注册",
            httpMethod = "POST", response =Msg.class )
    public Msg registeredController(@Valid UserDate userDate, BindingResult result, @Param("verificationCode") String verificationCode, HttpSession session) {
        if (!session.getAttribute("checkNumber").equals(verificationCode)) {
            logger.error("邮箱验证失败！");
            return Msg.fail().add("error", "邮箱验证失败！");
        }
        if (result.hasErrors()) {
            Map<String, Object> map = new HashMap<>();
            List<FieldError> errors = result.getFieldErrors();
            logger.error("注册失败！");
            for (FieldError fieldError : errors) {
                logger.error("错误的字段名：" + fieldError.getField());
                logger.error("错误信息：" + fieldError.getDefaultMessage());
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return Msg.fail().add("errorFields", map);
        } else {
            if (userDateService.registeredInsertService(userDate)) {
                logger.info("注册成功！");
                return Msg.success();
            } else {
                logger.info("注册失败,用户名已存在！");
                return new Msg().add("error", "用户名已存在！");
            }
        }
    }




    @ApiOperation(value = "登录页面跳转",httpMethod = "POST")
    @RequestMapping("/loginjump")
    public ModelAndView loginJump() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/account/land");
        logger.info("欢迎进入登录页面");
        return modelAndView;
    }


    /**
     *
     * @param userName
     * @param password
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/login")
    @ApiOperation(value = "用户登陆", notes = "不能为空",httpMethod = "POST",response =Msg.class )
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userName",
                    value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "password",
                    value = "用户密码", required = true, dataType = "String"),
    }
    )
    public Msg loginUserController(@Param("userName") String userName, @Param("password") String password, HttpServletRequest request) {

        HttpSession session = request.getSession();
        UserDate userDate = new UserDate();
        userDate.setPassword(password);
        userDate.setUserName(userName);

        if (userDateService.loginUser(userDate, session)) {
            logger.info("登陆成功！！");
            return Msg.success();
        } else {
            logger.info("登陆失败！！");
            return Msg.fail();
        }
    }

    /**
     * @param account
     * @param answer
     * @param problemId
     * @return Msg
     * <p>
     * 用户用密保信息获取密码
     */
    @ResponseBody
    @RequestMapping("/forgetPass")
    @ApiOperation(value = "用户用密保信息获取密码",httpMethod = "POST",response =Msg.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "account", value = "用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "answer", value = "密保答案", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "problemId", value = "密保问题id", required = true, dataType = "int")
    })
    public Msg forgetPass(@Param("account") String account, @Param("answer") String answer, @Param("problemId") int problemId) {
        return userDateService.getPass(account, answer, problemId);
    }

    /**
     * @param userDate
     * @param session
     * @return Msg
     * <p>
     * 修改密码
     */
    @ResponseBody
    @RequestMapping("/setPass")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userDate", value = "用户对象", required = true, dataType = "UserDate"),
    })
    @ApiOperation(value = "修改密码接口",httpMethod = "POST",response =Msg.class)
    public Msg setPass(UserDate userDate, HttpSession session) {
        return userDateService.setUserPassword(userDate);
    }

    /**
     * @param post
     * @param session
     * @return Msg
     * <p>
     * 发送邮箱接口
     */
    @ResponseBody
    @RequestMapping("/sentPost")
    @ApiOperation(value = "发送邮箱接口",httpMethod = "POST",response =Msg.class)
    @ApiImplicitParam(paramType = "query", name = "post", value = "待发送人的邮箱", required = true, dataType = "String")
    public Msg sendPost(@Param("post") String post, HttpSession session) {
        if (userDateService.sentEmail(session, post)) {
            return Msg.success();
        } else {
            return Msg.fail();
        }
    }

    /**
     * @param post
     * @param httpSession
     * @return
     */
    @ResponseBody
    @RequestMapping("/judgmentcode")
    @ApiOperation(value = "发送邮箱验证码接口",httpMethod = "POST",response =Msg.class)
    @ApiImplicitParam(paramType = "query", name = "post", value = "待发送人的邮箱", required = true, dataType = "String")
    public Msg judgmentCode(@Param("post") String post, HttpSession httpSession) {
        if (!httpSession.getAttribute("checkNumber").equals(post)) {
            return new Msg().add("error", "邮箱验证失败！");
        } else {
            return Msg.success();
        }
    }



    /**
     * @param lookHistory
     * @return Msg
     * <p>
     * 添加历史纪录
     */
    @ResponseBody
    @RequestMapping("/addHistory")
    @ApiOperation(value = "添加历史纪录接口",httpMethod = "POST",response =Msg.class)
    public Msg addHistory(LookHistory lookHistory) {
        return null;
    }

    /**
     * @return Msg
     * <p>
     * 清空历史纪录
     */
    @ResponseBody
    @RequestMapping("/deleteHistory")
    @ApiOperation(value = "清空历史接口",httpMethod = "POST",response =Msg.class)
    public Msg deleteHistory() {
        return null;
    }


    /**
     * @param carData
     * @return Msg
     * <p>
     * 添加购物车
     */
    @ResponseBody
    @RequestMapping("/addCar")
    @ApiOperation(value = "添加购物车接口",httpMethod = "POST",response =Msg.class)
    public Msg addCarData(CarData carData) {

        return null;
    }



    /**
     * @param carData
     * @return Msg
     * <p>
     * 删除购物车
     */
    @ApiOperation(value = "删除购物车接口",httpMethod = "POST",response =Msg.class)
    public Msg deleteCarData(CarData carData) {
        return null;
    }


    @ApiOperation(value = "查看个人订单",httpMethod = "POST",response = String.class)
    @RequestMapping("/myOrder")
    public String shoppingMyOrder(HttpSession session, Model model){
        UserDate userDate=(UserDate) session.getAttribute("user");
        model.addAttribute("orderAll",iOrderTransportDateService.selectUserIdOrderTransportDateService(userDate.getUserId()));
        return "my/myOrder";
    }


    @ApiOperation(value = "查看个人已完成订单",httpMethod = "POST",response = String.class)
    @RequestMapping("/willMyOrder")
    public String finishMyOrder(HttpSession session, Model model,@RequestParam(value = "page", defaultValue = "1") Integer page){
        PageHelper.startPage(page,8);
        UserDate userDate=(UserDate) session.getAttribute("user");
        PageInfo pageInfo=new PageInfo(iOrderTransportDateService.selectUserIdFinishOrderTransportDateService(userDate.getUserId()));
        model.addAttribute("orderAll",pageInfo);
        return "concern/concernShop";
    }


    @ApiOperation(value = "上传文件",httpMethod = "POST",response = Msg.class)
    @RequestMapping("/uploadPhoto")
    public String uploadPhoto(@Param("files")MultipartFile files,HttpSession session,HttpServletRequest request)throws IOException{
            Msg msg=userDateService.upLoad(files,session,request);
         return "redirect:/myVault";
    }

    @ApiOperation(value = "添加购物车",httpMethod = "POST",response = Msg.class)
    @RequestMapping("/shoppingCart")
    @ResponseBody
    public Msg shoppingCart(CarData data,HttpSession session){
        UserDate userDate=(UserDate) session.getAttribute("user");
        data.setStoreName(userDate.getUserId()+"");
        return iCarDataService.addCar(data);
    }

    @ApiOperation(value = "跳转加入购物车成功",httpMethod = "POST",response = Msg.class)
    @RequestMapping("/jumpShopping")
    public ModelAndView jumpWinAdd(int goodsId ){
    ModelAndView modelAndView=new ModelAndView();
    modelAndView.setViewName("buy/shoppingCart");
    GoodsData goodsData=goodsDateService.selectGoods(goodsId);
    modelAndView.addObject("likeDate",goodsDateService.selectGoodsShow(goodsDateService.selectDate(goodsData.getGoodsKind()),8));
    modelAndView.addObject("date",goodsData);
    return modelAndView;
    }

    @ApiOperation(value = "跳转购物车",httpMethod = "POST",response = Msg.class)
    @RequestMapping("/shoppingTrolley")
    public ModelAndView jumpCar(HttpSession session) {
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("buy/shoppingTrolley");
            if(session.getAttribute("user")==null){
            return modelAndView;
        }
        UserDate userDate=(UserDate) session.getAttribute("user");
        List<ShowDate> carData=iCarDataService.carList(userDate.getUserId());
        modelAndView.addObject("carDate",carData);
        modelAndView.addObject("hotGoods",goodsDateService.selectHotGoods());
        modelAndView.setViewName("buy/shoppingTrolley");
        return modelAndView;
    }

    @ApiOperation(value = "更新购物车",httpMethod = "POST",response = Msg.class)
    @RequestMapping("/upDateCar")
    public void upDateCar(CarData carData){
        iCarDataService.upDateCarNumber(carData);
    }
    @ApiOperation(value = "删除购物车",httpMethod = "POST",response = Msg.class)
    @RequestMapping("/deleteDateCar")
    public String delectCar(int orderId,HttpSession session){
        UserDate userDate=(UserDate)session.getAttribute("user");
        iCarDataService.deleteCar(orderId+"",userDate.getUserId());
        return "redirect:/user/shoppingTrolley";
    }



    @RequestMapping("/shoppingSettlement")
    public ModelAndView shoppingSettlement(HttpSession session){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("buy/shoppingSettlement");
        return modelAndView;
    }


    @RequestMapping("/addOrder")
    @ResponseBody
    public Msg addOrder(@RequestParam(value="array[]", required = false)List<String> array,HttpSession session){

            return iOrderTransportDateService.addAllOrder(array,session);
        }

    @RequestMapping("/buyGoodsOrder")
    public String buyGoodsOrder(@Param("provice")String provice,@Param("city")String city ,@Param("district")String district,@Param("town")String town,@Param("phone")String phone,@Param("perice")String perice,HttpSession session){
        List<OrderTransportData> list=(List<OrderTransportData>)session.getAttribute("orderDate");
        String postion=provice+" "+city+" "+district+" "+town ;
        System.out.println(postion);
        Calendar calendar=Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("dHhmm");
        String out_trade_no=format.format(calendar.getTime());
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        for (OrderTransportData orderTransportData:list){
            orderTransportData.setConsignTime(out_trade_no);
            orderTransportData.setBuyerMessage(postion);
            orderTransportData.setBuyerNick(phone);
        }
        iOrderTransportDateService.addPostDate(list);
        String url="redirect:/Alipay/goPay?perice="+perice+"&subject=win&out_trade_no="+out_trade_no;
//        iOrderTransportDateService
        return url;
    }

    @RequestMapping("/upPoint")
    public Msg reSetPoint(UserDate userDate){
        return  userDateService.setPoint(userDate);
    }

    @RequestMapping("/nowBuyGoods")
    @ResponseBody
    public Msg  buyGoods(@Param("number")int number,@Param("goodsId")int goodsId,@Param("perice")float perice ,HttpSession session){
        UserDate userDate=(UserDate)session.getAttribute("user");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar=Calendar.getInstance();
        String timeDate=simpleDateFormat.format(calendar.getTime());
        GoodsData data=goodsDateService.selectGoods(goodsId);
        float onePerice=perice*number;
        OrderTransportData orderTransportData=new OrderTransportData(onePerice,false,timeDate,userDate.getUserId(),number,perice,data.getPhotoUrl(),data.getGoodsName(),data.getId(),"0");
        List<OrderTransportData> OrderDate=new ArrayList<OrderTransportData>();
        OrderDate.add(orderTransportData);
        int select=orderTransportDataMapper.insertSelective(orderTransportData);
        if(select==0){
            return Msg.fail();
        }
        session.setAttribute("orderDate",OrderDate);
        session.setAttribute("money",onePerice);
        return Msg.success();
    }


    @RequestMapping("/myVault")
    public String jumpMyVault(){
        return "my/MyVault";
    }

    @RequestMapping("/finishOrder")
    public String finishOrder(HttpSession session,@Param("orderId")String orderId){
        System.out.println(orderId+"====");
        OrderTransportData orderTransportData=iOrderTransportDateService.selectOrderIdOrderTransportDateService(Integer.parseInt(orderId));
        List<OrderTransportData> list=new ArrayList();
        list.add(orderTransportData);
        session.setAttribute("orderDate",list);
        session.setAttribute("money",orderTransportData.getPayment());
        return "buy/shoppingSettlement";
    }

    @RequestMapping("/endOrder")
    public String endOrder(int id){
        iOrderTransportDateService.endOrder(id);
        return "redirect:/user/myOrder";
    }
}

